package com.xuecheng.managecmsclient.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.managecmsclient.dao.CmsPageRepository;
import com.xuecheng.managecmsclient.dao.CmsSiteRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author jl
 * @description
 * @date 2019-08-19 16:54
 */
@Service
@Slf4j
public class CmsPageService {
    @Autowired
    private CmsPageRepository cmsPageRepository;
    @Autowired
    private CmsSiteRepository cmsSiteRepository;
    @Autowired
    private GridFSBucket gridFSBucket;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    public void savePageToServerPath(String pageId) {
        //得到html文件的id,从cmsPage中获取htmlFileId
        CmsPage cmsPage = findCmsPageByPageId(pageId);
        if (cmsPage == null) {
            log.error("未找到页面,pageId={}", pageId);
            return;
        }
        //通过htmlFileId从gridFS中查询html文件(gridFS中的页面是模板+数据=静态化后的页面,即完整的页面)
        String htmlFileId = cmsPage.getHtmlFileId();
        InputStream inputStream = getInputStreamFileById(htmlFileId);
        if (inputStream == null) {
            log.error("getInputStreamFileById return null,htmlFileId:{}",htmlFileId);
            return;
        }
        //得到站点的物理路径
        CmsSite cmsSite = findCmsSiteBySiteId(cmsPage.getSiteId());
        if (cmsSite == null) {
            log.error("站点信息为空,siteId:{}",cmsPage.getSiteId());
            return;
        }
        String sitePhysicalPath = cmsSite.getSitePhysicalPath();
        //得到页面的物理路径
        String pagePath = sitePhysicalPath + cmsPage.getPagePhysicalPath() + cmsPage.getPageName();
        //将html文件保存到服务器物理路径上
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(pagePath));
            IOUtils.copy(inputStream,fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据页面id查询页面信息
     *
     * @param pageId
     * @return
     */
    private CmsPage findCmsPageByPageId(String pageId) {
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        return optional.orElse(null);
    }

    /**
     * 根据站点id查询站点信息
     */
    private CmsSite findCmsSiteBySiteId(String siteId) {
        Optional<CmsSite> optional = cmsSiteRepository.findById(siteId);
        return optional.orElse(null);
    }

    /**
     * 根据文件id获取文件内容
     */
    private InputStream getInputStreamFileById(String fileId) {
        try {
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
            GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
            return gridFsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
